const app = getApp()
const {
  ActivityModel
} = require('../../../utils/activity-model.js')
const activityModel = new ActivityModel()
const {
  MarketingModel
} = require('../../../utils/marketing-model.js');
var marketingModel = new MarketingModel();
const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: 1,
    modelType: '1',
    activityId: '',
    merchantId: '',
    shopId: '',
    shopName: '',
    title: '',
    phoneNumber: '',
    isLogin: true,
    ruleShow: false,
    activityInfo: {},
    tabIdx: 0,
    tabs: [{
        label: '全国排行榜',
        value: 0
      },
      {
        label: '区域排行榜',
        value: 1
      },
      {
        label: '门店排行榜',
        value: 2
      }
    ],
    myRankInfo: {},
    joinWarZone: true,
    goldRecordRankList: [],
    partitionCoinWinList: [],
    rankShowMore: false,
    day: '0',
    hou: '00',
    min: "00",
    sec: "00",
    timerName: "", //计时器名字
    awardeList: [], //查看礼包奖品
    shopData: [], //门店列表
    selectShopInfo: {},
    isDisabled: false,
    giftbagShow: false, //扫码礼包
    debrisData: {}, //碎片列表
    debrisShow: false, //扫码碎片
    prizeInfo: {},
    gatherShow: false,
    activityInfoStatus: 0,
    activityEnd: '', //结束时间
    activityStart: '', //开始时间
    isShop: false,
    ruleActivityStart: '',
    ruleActivityEnd: '',
    isEnd: false,
    authShow: false,
    isLogin: false,
    memberId: ''
  },

  lookRule(e) {
    let type = e.currentTarget.dataset.type; //卡号
    this.setData({
      modelType: type,
      ruleShow: true
    })
  },
  closeRule() {
    this.setData({
      ruleShow: false
    })
  },

  tabChange(e) {
    const {
      index
    } = e.currentTarget.dataset
    if (index !== this.data.tabIdx) {
      this.setData({
        tabIdx: index
      })
      this.getCoinInfo()
    }
  },
  changeMore() {
    this.setData({
      rankShowMore: !this.data.rankShowMore
    })
  },
  /**
   *微信会员信息
   */
  getUserInfo: function () {
    var that = this;
    if (that.data.isLogin) {
      that.getAppletDetail()
      memberModel.userInfo({
        merchantId: that.data.merchantId
      }).then(data => {
        that.setData({
          memberId: data.memberId || "", //会员ID
        });
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      that.setData({
        authShow: true
      })
    }
  },
  //排行榜
  getCoinInfo() {
    const type = this.data.tabs[this.data.tabIdx].value
    activityModel.appletRank({
      queryType: type,
      shopId: this.data.shopId,
      phoneNumber: this.data.phoneNumber,
      activityId: this.data.activityId
    }).then(data => {
      if (type !== 1) {
        data.joinWarZone = true
      }
      let activityInfoStatus = 1
      if (this.data.activityInfo.activityStatus == 1 || (data && data.partitionCoinWinList && data.partitionCoinWinList.length > 0)) {
        activityInfoStatus = 1
      } else {
        activityInfoStatus = 2
      }
      this.setData({
        joinWarZone: !!data.joinWarZone,
        goldRecordRankList: data.partitionCoinRankRecordList || [],
        partitionCoinWinList: data.partitionCoinWinList || [],
        myRankInfo: data,
        activityInfoStatus: activityInfoStatus
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  //礼包实物记录
  getAppletAwarde() {
    activityModel.appletAwarde({
      activityId: this.data.activityId
    }).then(data => {
      this.setData({
        awardeList: data || []
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  /**
   * 碎片详情页
   */
  goPrizePiecesInfo: function (event) {
    var type = event.currentTarget.dataset.type; //页面类型
    var activityId = event.currentTarget.dataset.id; //核销记录id || 奖品id
    var activityStatus = event.currentTarget.dataset.status; //状态
    if (type == 2) {
      wx.navigateTo({
        url: `/pages/memberCenter/discountCoupon/index`
      })
    } else {
      if (activityId) {
        wx.navigateTo({
          url: `/pages/memberCenter/prize/prizePiecesInfo/index?type=${type}&activityId=${activityId}&activityStatus=${activityStatus}&activityCardType=5`
        })
      }
    }
  },
  /**
   * 兑换
   */
  exchangeCoin: function (event) {
    var shopId = event.currentTarget.dataset.id; //页面类型
    let that = this;
    wx.showModal({
      title: '确认飞豆兑换？',
      success(res) {
        if (res.confirm) {
          that.setData({
            isDisabled: true
          })
          activityModel.appletExchange({
            activityId: that.data.activityId,
            shopId: shopId,
            phoneNumber: that.data.phoneNumber,
          }).then(data => {
            wx.setStorageSync('selectShopId', shopId);
            if (data) {
              that.setData({
                debrisData: data,
                giftbagShow: true,
                isDisabled: false
              });
            } else {
              that.setData({
                debrisData: {},
                giftbagShow: false,
                isDisabled: false
              });
            }
          }).catch(err => {
            that.setData({
              debrisData: {},
              giftbagShow: false,
              isDisabled: false
            });
            wx.showToast({
              title: `${err.error}`,
              icon: 'none'
            })
          })
        }
      }
    })
  },
  //关闭大礼包
  closeGiftbag() {
    var that = this;
    that.setData({
      giftbagShow: false
    }, function () {
      if (that.data.debrisData.isMissFragment) {
        that.setData({
          debrisShow: true
        })
      } else {
        that.getAppletDetail()
      }
    })
  },
  //碎片集合
  closeDebris() {
    this.setData({
      debrisShow: false
    })
    this.getAppletDetail()
  },
  //去点亮
  goIllume() {
    var that = this;
    that.setData({
      debrisShow: false,
    }, function () {
      that.getMemberLight();
    })
  },
  /**
   * 去点亮
   */
  getMemberLight: function () {
    var that = this;
    var item = that.data.debrisData.activityAward;
    var param = {};
    param.merchantId = item.merchantId; //商户id
    param.activityAwardId = item.activityAwardId; //奖品id
    marketingModel.memberLight(param).then(data => {
      if (data) {
        that.setData({
          prizeInfo: data,
          gatherShow: true
        });
      } else {
        that.setData({
          prizeInfo: {},
          gatherShow: false
        });
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  //去点亮
  closeIllume() {
    var that = this;
    that.setData({
      debrisShow: false,
      gatherShow: false
    })
    that.getAppletDetail()
  },
  //去兑奖台兑换
  goExchange() {
    var that = this;
    that.setData({
      gatherShow: false
    }, function () {
      if (that.data.prizeInfo.activityType == 1) { //活动类型  1:老集卡 2:全国集卡（抽奖券） 3:达人机（幸运福袋）
        wx.redirectTo({
          url: `/pages/memberCenter/prize/prizeCancellation/index?activityVerificationId=${that.data.prizeInfo.activityVerificationId}`
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      activityId: options.activityId,
      shopId: options.shopId,
      shopName: options.shopName
    })
  },
  onShow() {
    let that = this;
    app.getInfo().then(({
      data
    }) => {
      that.setData({
        isLogin: data.login,
        phoneNumber: data.appletMobile,
        merchantId: data.merchantId
      }, function () {
        that.getUserInfo();
      })
    })
  },

  /**
   * 活动详情
   */
  getAppletDetail() {
    let that = this
    activityModel.appletDetail({
      activityId: that.data.activityId,
      shopId: that.data.shopId,
      merchantId: that.data.merchantId
    }).then(data => {
      let shopId = wx.getStorageSync('selectShopId')
      if (shopId) {
        shopId = wx.getStorageSync('selectShopId')
      } else {
        shopId = that.data.shopId
      }
      let shopInfo = []
      if (shopId) {
        shopInfo = data.lotteryMapResult.filter(item => item.shopId == shopId) || []
        if (shopInfo.length == 0) {
          shopInfo = data.lotteryMapResult || []
        }
      } else {
        shopInfo = data.lotteryMapResult || []
      }
      that.setData({
        activityInfo: data || {},
        shopData: data.lotteryMapResult || [],
        selectShopInfo: shopInfo[0] || {},
        title: data.activityName,
        activityEnd: data.activityEnd.replace(/-/g, '/') || '',
        ruleActivityStart: data.activityStart.replace(/-/g, '.') || '',
        ruleActivityEnd: data.activityEnd.replace(/-/g, '.') || '',
      }, function () {
        let nowTime = new Date().getTime(); //现在时间（时间戳）
        let roundEndTime = new Date(that.data.activityEnd).getTime();
        if (data.activityStatus === 1 && roundEndTime > nowTime) {
          that.setData({
            isEnd: false
          })
          that.countDown()
        } else {
          that.setData({
            isEnd: true
          })
        }
        let isDisabled = false;
        let lotteryCount = shopInfo.length > 0 ? parseInt(shopInfo[0].lotteryCount) : 0
        let exchangeCostLottery = parseInt(data.exchangeCostLottery) || 0
        if (lotteryCount < exchangeCostLottery || this.data.isEnd) {
          isDisabled = true;
        } else {
          isDisabled = false;
        }
        that.setData({
          isDisabled: isDisabled
        })
      })
      wx.setNavigationBarTitle({
        title: data.activityName
      })
      that.getCoinInfo()
      that.getAppletAwarde()
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  // 授权成功的回调
  loginSucceed: function () {
    let that = this
    app.getInfo().then(data => {
      that.setData({
        isLogin: data.data.login,
        phoneNumber: data.data.appletMobile,
        merchantId: data.data.merchantId
      }, function () {
        that.getUserInfo()
      })
    })
  },
  showShop: function (event) {
    this.setData({
      isDisabled: !this.data.isDisabled,
      isShop: !this.data.isShop
    })
  },
  selectShop: function (event) {
    let shopInfo = event.currentTarget.dataset.id; //页面类型
    let isDisabled = false;
    let lotteryCount = parseInt(shopInfo.lotteryCount) || 0
    let exchangeCostLottery = parseInt(this.data.activityInfo.exchangeCostLottery) || 0
    if (lotteryCount < exchangeCostLottery || this.data.isEnd) {
      isDisabled = true;
    } else {
      isDisabled = false;
    }
    this.setData({
      isDisabled: isDisabled,
      selectShopInfo: shopInfo,
      isShop: false
    })
  },
  // 倒计时
  countDown: function () {
    var that = this;
    var nowTime = new Date().getTime(); //现在时间（时间戳）
    var endTime = new Date(that.data.activityEnd).getTime(); //结束时间（时间戳）
    var time = (endTime - nowTime) / 1000; //距离结束的毫秒数
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    day = that.timeFormin(day);
    hou = that.timeFormin(hou);
    min = that.timeFormin(min);
    sec = that.timeFormin(sec);
    that.setData({
      day: that.timeFormat(day),
      hou: that.timeFormat(hou),
      min: that.timeFormat(min),
      sec: that.timeFormat(sec)
    })
    // 每1000ms刷新一次
    if (time > 0) {
      that.setData({
        countDown: true
      })
      that.setData({
        timerName: setTimeout(function () { //这里把setInterval赋值给变量名为timer的变量
          that.countDown()
        }, 1000)
      })
    } else {
      that.getAppletDetail();
      clearInterval(that.data.timerName);
      that.setData({
        countDown: false
      })
    }
  },
  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },
  onShareAppMessage() {
    console.log(`pages/activity/gameCoin/index?shareMemberId=${this.data.memberId}&shopId=${this.data.shopId}&activityId=${this.data.activityId}&shopName=${this.data.shopName}&isShare=1`)
    return {
      title: this.data.activityInfo.activityName,
      imageUrl: '/images/activity/gamecoin/share.png',
      path: `pages/activity/gameCoin/index?shareMemberId=${this.data.memberId}&shopId=${this.data.shopId}&activityId=${this.data.activityId}&shopName=${this.data.shopName}&isShare=1`
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setStorageSync('selectShopId', null);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.setStorageSync('selectShopId', null);
  },
})